package com.imooc.liu.shiroimooc.realm;

import com.imooc.liu.shiroimooc.model.Permission;
import com.imooc.liu.shiroimooc.model.Role;
import com.imooc.liu.shiroimooc.model.User;
import com.imooc.liu.shiroimooc.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 从session中拿到user对象
        User user = (User) principalCollection.fromRealm(this.getName()).iterator().next();
        List<String> roleNameList = new ArrayList<>();
        List<String> permissionList = new ArrayList<String>();
        Set<Role> roleSet = user.getRoles();
        if (CollectionUtils.isNotEmpty(roleSet)) {
            for(Role role: roleSet) {
                roleNameList.add(role.getRname());
                Set<Permission> permissions = role.getPermissions();
                if (CollectionUtils.isNotEmpty(permissions)) {
                    for (Permission permission: permissions) {
                        permissionList.add(permission.getName());
                    }
                }
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 添加权限
        info.addStringPermissions(permissionList);
        // 添加角色
        info.addRoles(roleNameList);
        return info;
    }

    // 登陆认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 拿到用户登陆的token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        User user = userService.findByUsername(username);

        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
    }
}
